<template>
    <view class="bg-[#F3F5F9] ">
        <!-- 顶部切换栏 -->
        <view class="px-[40rpx] pt-[20rpx]">
            <view class="flex gap-[20rpx]">
                <view v-for="(item, index) in tabList" :key="index"
                    class="flex-1 h-[80rpx] rounded-[100rpx] flex items-center justify-center"
                    :class="currentTab === index ? 'bg-black text-white' : 'bg-white text-[#333]'"
                    @click="changeTab(index)">
                    <text :class="currentTab === index ? 'text-white' : 'text-[#333]'">{{ item.name }}</text>
                </view>
            </view>
        </view>

        <!-- 我创建的家庭 - -->
        <swiper v-if="currentTab === 0" class="family-swiper" :current="currentFamily" @change="onFamilyChange">
            <!-- 现有家庭滑块 -->
            <swiper-item v-for="(family, familyIndex) in myFamilies" :key="familyIndex">
                <view style="border: 2rpx solid #FFFFFF" class="mx-[52rpx] mt-[42rpx] rounded-[24rpx]">
                    <!-- 家庭内容 -->
                    <view class="flex items-center pl-[16rpx]">
                        <image src="@/static/images/img/lfangz.png" class="w-[170rpx] h-[170rpx] "></image>
                        <view class="ml-[22rpx]">
                            <view class="text-[28rpx] text-[#000000] font-[PingFang SC] font-[500]">{{ family.name }}
                            </view>
                            <view  @click="goToPetManagement(family.id)" style="border: 2rpx solid #FFFFFF;"
                                class="text-[24rpx] flex items-center bg-[#DBE3FF] text-[#4761F4] py-[8rpx] pl-[18rpx] pr-[12rpx] font-[500] font-[PingFang SC] mt-[14rpx] rounded-[80rpx]">
                                <view class="mr-[12rpx]">
                                    当前家庭{{ family.petCount }}个宠物
                                </view>
                                <image src="@/static/images/icon/an.png" class="w-[32rpx] h-[32rpx]"></image>
                            </view>
                        </view>
                    </view>

                    <view class="text-[24rpx] px-[24rpx] text-[#666666] font-[500] font-[PingFang SC]">共{{
                    familypeople }}个家人</view>
                    <view class="mt-[8rpx] px-[24rpx]">
                        <!-- 家庭成员列表（使用currentFamilyMembers渲染） -->
                        <view v-for="(member, memberIndex) in currentFamilyMembers" :key="memberIndex"
                            class="flex items-center justify-between bg-[#FFFFFF] rounded-[24rpx] py-[20rpx] mb-[20rpx]">
                            <image :src="member.uavatar" class="w-[88rpx] h-[88rpx] rounded-[50%] ml-[20rpx]"></image>
                            <text class="text-[28rpx] font-[500] ml-[-250rpx] text-[#000000]">{{ member.uname }}</text>
                            <image src="@/static/images/img/deleate.png" class="w-[64rpx] h-[64rpx] mr-[20rpx]"
                                @click="handleDeleteMember(member.uid, family.id)"></image>
                        </view>
                        <view
                            class="mt-[92rpx] jiesan ml-[-24rpx] text-[28rpx] text-[#FFFFFF] font-[600] font-[PingFang SC] flex justify-center items-center"
                            @click="handleDisbandFamily(family.id)">
                            解散家庭
                        </view>
                    </view>
                </view>
            </swiper-item>

            <!-- 添加创建家庭滑块 -->
            <swiper-item>
                <view class="mx-[52rpx] mt-[42rpx] flex flex-col items-center justify-center h-[600rpx]">
                    <image src="@/static/images/img/lfangz.png" class="w-[200rpx] h-[200rpx] mb-[40rpx]"
                        mode="aspectFit"></image>
                    <text class="text-[28rpx] text-[#666] mb-[60rpx]">创建一个新的家庭</text>
                    <view class="w-[538rpx] h-[108rpx] text-[#000000]" style="border-radius: 400rpx;"
                        @click="push('/pages_cw/createhome/createhome')">
                        <image src="@/static/images/img/createhome.png" class="w-[538rpx] h-[108rpx]"></image>
                    </view>
                </view>
            </swiper-item>
        </swiper>

        <!-- 滑块指示器 -->
        <view v-if="currentTab === 0" class="indicator-container">
            <view v-for="(_, index) in [...myFamilies, 'create']" :key="index" class="indicator"
                :class="{ 'active': index === currentFamily }">
            </view>
        </view>

        <!-- 我加入的家庭 - 可滑动 -->
        <swiper v-if="currentTab === 1" class="family-swiper" :current="currentJoinFamily" @change="onJoinFamilyChange">
            <swiper-item v-for="(family, familyIndex) in joinFamilies" :key="familyIndex">
                <view style="border: 2rpx solid #FFFFFF" class="mx-[52rpx] mt-[42rpx] rounded-[24rpx]">
                    <!-- 家庭信息 -->
                    <view class="flex items-center pl-[16rpx]">
                        <image src="@/static/images/img/lfangz.png" class="w-[170rpx] h-[170rpx] "></image>
                        <view class="ml-[22rpx]">
                            <view class="text-[28rpx] text-[#000000] font-[PingFang SC] font-[500]">{{ family.name }}
                            </view>
                            <view @click="goToPetManagement(family.id)" style="border: 2rpx solid #FFFFFF;"
                                class="text-[24rpx] flex items-center bg-[#DBE3FF] text-[#4761F4] py-[8rpx] pl-[18rpx] pr-[12rpx] font-[500] font-[PingFang SC] mt-[14rpx] rounded-[80rpx]">
                                <view class="mr-[12rpx]" >
                                    当前家庭{{ family.petCount }}个宠物
                                </view>
                                <image src="@/static/images/icon/an.png" class="w-[32rpx] h-[32rpx]"></image>
                            </view>
                        </view>
                    </view>

                    <!-- 创建人 -->
                    <view class="px-[30rpx] ">
                        <view class="text-[24rpx] text-[#666666] font-[500] mb-[8rpx]">创建人</view>
                        <view
                            class="flex items-center bg-[#FFFFFF] rounded-[24rpx] py-[20rpx] mb-[20rpx] border border-[#F6F6F6]">
                            <image :src="(currentJoinFamilyMembers.find(m => m.role === 1) || {}).uavatar"
                                class="w-[88rpx] h-[88rpx] rounded-[50%] ml-[20rpx]"></image>
                            <text class="text-[28rpx] font-[500] ml-[20rpx] text-[#000000]">{{ family.createBy }}</text>
                        </view>
                    </view>

                    <!-- 家庭成员 -->
                    <view class="px-[24rpx] pb-[30rpx]">
                        <view class="text-[24rpx] text-[#666666] font-[500] mb-[20rpx]">家庭成员</view>

                        <view v-for="(member, memberIndex) in currentJoinFamilyMembers" :key="memberIndex"
                            class="flex items-center bg-[#FFFFFF] rounded-[24rpx] py-[20rpx] mb-[20rpx] border border-[#F6F6F6]"
                            :class="{ 'border-[#4761F4] border-2': memberIndex === (currentJoinFamilyMembers.length - 1) }">
                            <image :src="member.uavatar" class="w-[88rpx] h-[88rpx] rounded-[50%] ml-[20rpx]"></image>
                            <text class="text-[28rpx] font-[500] ml-[20rpx] text-[#000000]">{{ member.uname }}</text>
                        </view>
                    </view>
                    <view @click="handletc(family.id)"
                        class="mt-[44rpx] jiesan text-[28rpx] text-[#FFFFFF] font-[600] font-[PingFang SC] flex justify-center items-center">
                        退出家庭
                    </view>
                </view>
            </swiper-item>
        </swiper>

        <!-- 加入的家庭滑块指示器 -->
        <view v-if="currentTab === 1 && joinFamilies.length > 1" class="indicator-container">
            <view v-for="(_, index) in joinFamilies" :key="index" class="indicator"
                :class="{ 'active': index === currentJoinFamily }">
            </view>
        </view>

        <!-- 底部按钮 -->

        <view v-if="currentTab === 0" class="w-[538rpx] h-[108rpx] text-[#000000] fixed bottom-[80rpx]"
            style="border-radius: 400rpx;left: 50%; transform: translateX(-50%)" @click="showInviteDialogWithCode">
            <image src="@/static/images/img/yqcy.png" class="w-[538rpx] h-[108rpx]"></image>
        </view>

        <view v-else class="w-[538rpx] h-[108rpx] text-[#000000] fixed bottom-[80rpx]"
            style="border-radius: 400rpx;left: 50%; transform: translateX(-50%)">
            <image @click="push('/pages_cw/joinfamily/joinfamily')" src="@/static/images/img/jrjt.png"
                class="w-[538rpx] h-[108rpx]"></image>
        </view>
    </view>

    <!-- 邀请码弹窗 -->
    <up-popup :show="showInviteDialog" @close="showInviteDialog = false" mode="center" :closeOnClickOverlay="true"
        :customStyle="{
                    width: '650rpx',
                    background: 'linear-gradient(180deg, rgba(230, 230, 250, 1) 0%, rgba(255, 255, 255, 1) 40%)',
                    borderRadius: '24rpx',
                    padding: '40rpx 30rpx',

                }">
        <!-- 弹窗内容保持不变 -->
        <view class="relative">
            <!-- 关闭按钮 -->
            <view class="absolute right-[0rpx] top-[0rpx]" @click="showInviteDialog = false">
                <text class="text-[40rpx] text-[#999]">×</text>
            </view>
            <!-- 弹窗标题 -->
            <view class="text-center text-[32rpx] font-[500] mb-[40rpx]">您的邀请码</view>
            <!-- 邀请码 -->
            <view class="text-center text-[28rpx] font-[500] mb-[40rpx]">
                {{ inviteCode }}
            </view>
            <!-- 复制按钮 -->
            <view class="mt-[20rpx]">
                <button
                    class="w-full h-[90rpx] bg-[#C0FF00] text-[#000] rounded-[100rpx] flex items-center justify-center font-bold"
                    @click="copyInviteCode">
                    复制邀请码
                </button>
            </view>
        </view>
    </up-popup>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import useUserStore from '@/store/modules/user';
import { onShow, onLoad } from '@dcloudio/uni-app';
import { getFamilyList, getFamilyMemberList, deleteFamilyMember, disbandFamily } from '@/api/home';
const userStore = useUserStore();
const familypeople = ref();//家庭成员数
const familypets = ref();//家庭宠物数

// 标签页数据
const tabList = ref([
    { name: '我创建的家庭', type: 'my' },
    { name: '我加入的家庭', type: 'join' }
]);

// 当前选中的标签页
const currentTab = ref(0);

// 当前选中的家庭索引
const currentFamily = ref(0);
const currentJoinFamily = ref(0);

// 家庭数据
const myFamilies = ref([]);
const joinFamilies = ref([]);

// 接收页面参数
onLoad((options) => {
    if (options.tab) {
        currentTab.value = parseInt(options.tab);
        // 根据标签页加载对应数据
        if (currentTab.value === 0) {
            fetchMyFamilies();
        } else {
            fetchJoinFamilies();
        }
    }
});

// 获取我创建的家庭列表
const fetchMyFamilies = async () => {
    try {
        const params = {
            uid: userStore.userId,
            type: 'my'
        };
        const res = await getFamilyList(params);
        if (res.code === 200) {
            myFamilies.value = res.rows || [];
            console.log('获取我创建的家庭成功:', myFamilies.value);
        } else {
            console.error('获取我创建的家庭失败:', res.msg);
            uni.showToast({
                title: res.msg || '获取家庭列表失败',
                icon: 'none'
            });
        }
    } catch (error) {
        console.error('获取我创建的家庭异常:', error);
        uni.showToast({
            title: '网络异常，请稍后重试',
            icon: 'none'
        });
    }
};

// 获取我加入的家庭列表
const fetchJoinFamilies = async () => {
    try {
        const params = {
            uid: userStore.userId,
            type: 'join'
        };
        const res = await getFamilyList(params);
        if (res.code === 200) {
            joinFamilies.value = res.rows || [];

            console.log('获取我加入的家庭成功:', joinFamilies.value);
        } else {
            console.error('获取我加入的家庭失败:', res.msg);
            uni.showToast({
                title: res.msg || '获取家庭列表失败',
                icon: 'none'
            });
        }
    } catch (error) {
        console.error('获取我加入的家庭异常:', error);
        uni.showToast({
            title: '网络异常，请稍后重试',
            icon: 'none'
        });
    }
};

// 切换标签页
const changeTab = (index) => {
    currentTab.value = index;
    if (index === 0) {
        fetchMyFamilies();
    } else {
        fetchJoinFamilies();
    }
};

// 家庭成员数据
const currentFamilyMembers = ref([]);//我创建的家庭当前选中家庭的成员列表
const currentJoinFamilyMembers = ref([]); //存储我加入的家庭”当前选中家庭的成员列表

// 获取当前滑块家庭成员
const fetchCurrentFamilyMembers = async () => {
    // 判断当前滑块是否为“创建家庭”滑块
    if (currentFamily.value >= myFamilies.value.length) {
        currentFamilyMembers.value = [];
        return;
    }
    const family = myFamilies.value[currentFamily.value];
    if (!family || !family.id) {
        currentFamilyMembers.value = [];
        return;
    }
    try {
        const res = await getFamilyMemberList({ familyId: family.id });
        if (res.code === 200) {
            currentFamilyMembers.value = res.rows || [];
            familypeople.value = res.total || 0;
        } else {
            currentFamilyMembers.value = [];
            uni.showToast({
                title: res.msg || '获取家庭成员失败',
                icon: 'none'
            });
        }
    } catch (error) {
        currentFamilyMembers.value = [];
        uni.showToast({
            title: '网络异常，请稍后重试',
            icon: 'none'
        });
    }
};

// 家庭滑动切换事件
const onFamilyChange = (e) => {
    currentFamily.value = e.detail.current;
    fetchCurrentFamilyMembers();
};

// 获取当前“我加入的家庭”滑块的成员
const fetchCurrentJoinFamilyMembers = async () => {
    if (currentJoinFamily.value >= joinFamilies.value.length) {
        currentJoinFamilyMembers.value = [];
        return;
    }
    const family = joinFamilies.value[currentJoinFamily.value];
    if (!family || !family.id) {
        currentJoinFamilyMembers.value = [];
        return;
    }
    try {
        const res = await getFamilyMemberList({ familyId: family.id });
        if (res.code === 200) {
            currentJoinFamilyMembers.value = res.rows || [];
        } else {
            currentJoinFamilyMembers.value = [];
            uni.showToast({
                title: res.msg || '获取家庭成员失败',
                icon: 'none'
            });
        }
    } catch (error) {
        currentJoinFamilyMembers.value = [];
        uni.showToast({
            title: '网络异常，请稍后重试',
            icon: 'none'
        });
    }
};
// 邀请码弹窗相关
const showInviteDialog = ref(false);
const inviteCode = ref('');

// 显示邀请码弹窗，并设置当前家庭的邀请码
const showInviteDialogWithCode = () => {
    // 判断当前滑块是否为“创建家庭”滑块
    if (currentFamily.value >= myFamilies.value.length) {
        uni.showToast({
            title: '请先选择或创建一个家庭',
            icon: 'none'
        });
        return;
    }
    const family = myFamilies.value[currentFamily.value];
    inviteCode.value = family && family.code ? family.code : '暂无邀请码';
    showInviteDialog.value = true;
};
// 复制邀请码
const copyInviteCode = () => {
    uni.setClipboardData({
        data: inviteCode.value,
        success: () => {
            uni.showToast({
                title: '邀请码已复制',
                icon: 'success'
            });
        }
    });
};

// 加入的家庭滑动切换事件
const onJoinFamilyChange = (e) => {
    currentJoinFamily.value = e.detail.current;
    fetchCurrentJoinFamilyMembers();
};

// 页面加载和显示时获取“我加入的家庭”成员
onMounted(() => {
    fetchMyFamilies().then(() => {
        fetchCurrentFamilyMembers();
    });
    fetchJoinFamilies().then(() => {
        fetchCurrentJoinFamilyMembers();
    });
});

onShow(() => {
    if (currentTab.value === 0) {
        fetchMyFamilies().then(() => {
            fetchCurrentFamilyMembers();
        });
    } else {
        fetchJoinFamilies().then(() => {
            fetchCurrentJoinFamilyMembers();
        });
    }
});

// 删除家庭成员
const handleDeleteMember = async (memberId, famId) => {
    console.log('删除家庭成员:', memberId);
    if (memberId == userStore.userId) {
        uni.showToast({
            title: '不能删除创建人，只能解散家庭',
            icon: 'none'
        });
        return;
    }
    uni.showModal({
        title: '提示',
        content: '确定要删除该家庭成员吗？',
        success: async (res) => {
            if (res.confirm) {
                try {
                    const data = {
                        uid: memberId,
                        familyId: famId
                        // familyId: myFamilies.value[currentFamily.value].id

                    };
                    const result = await deleteFamilyMember(data);
                    if (result.code === 200) {
                        uni.showToast({ title: '删除成功', icon: 'success' });
                        fetchCurrentFamilyMembers();
                    } else {
                        uni.showToast({ title: result.msg || '删除失败', icon: 'none' });
                    }
                } catch (e) {
                    uni.showToast({ title: '网络异常', icon: 'none' });
                }
            }
        }
    });
};
// 解散家庭
const handleDisbandFamily = (familyId) => {
    console.log('解散家庭:', familyId);
    if (!familyId) {
        uni.showToast({
            title: '未找到家庭ID',
            icon: 'none'
        });
        return;
    }
    uni.showModal({
        title: '提示',
        content: '确定要解散该家庭吗？',
        success: async (res) => {
            if (res.confirm) {
                try {
                    const result = await disbandFamily(familyId);
                    if (result.code === 200) {
                        uni.showToast({ title: '解散成功', icon: 'success' });
                        fetchMyFamilies();
                        currentFamily.value = 0;
                        currentFamilyMembers.value = [];
                    } else {
                        uni.showToast({ title: result.msg || '解散失败', icon: 'none' });
                    }
                } catch (e) {
                    uni.showToast({ title: '网络异常', icon: 'none' });
                }
            }
        }
    });
};
//退出家庭
const handletc = async (famId) => {
    const data = {
        uid: userStore.userId,
        familyId: famId
        // familyId: myFamilies.value[currentFamily.value].id
    };
    deleteFamilyMember(data).then((res) => {
        if (res.code === 200) {
            uni.showToast({ title: '退出成功', icon: 'success' });
            // 刷新“我加入的家庭”列表和成员
            fetchJoinFamilies().then(() => {
                fetchCurrentJoinFamilyMembers();
            });
            // currentJoinFamily.value = 0;
            // currentJoinFamilyMembers.value = [];
        } else {
            uni.showToast({ title: res.msg || '退出失败', icon: 'none' });
        }
    }).catch((error) => {
        uni.showToast({ title: '网络异常', icon: 'none' });
    });
};
// 家庭宠物跳转
const goToPetManagement = (familyId) => {
    uni.navigateTo({
        url: `/pages_cw/petmanagement/petmanagement?familyId=${familyId}`
    });
};
</script>

<style scoped lang="scss">
.family-swiper {
    height: 1082rpx;
}

.indicator-container {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 48rpx;
    gap: 16rpx;
}

.indicator {
    width: 40rpx;
    height: 8rpx;
    background-color: #D9D9D9;
    border-radius: 4rpx;
    transition: all 0.3s;
}

.indicator.active {
    width: 60rpx;
    background-color: #000000;
}

.jiesan {
    width: 642rpx;
    height: 108rpx;
    border-radius: 0rpx 0rpx 24rpx 24rpx;
    background: linear-gradient(90deg, #4761F4 3%, #963BFF 99%);
    box-sizing: border-box;
    border: 2rpx solid #FFFFFF;
    box-shadow: 0rpx 4rpx 34rpx 0rpx rgba(0, 0, 0, 0.0215);
}
</style>